// hooks/useWebSocketReceiver.ts
import { useEffect, useRef, useMemo } from "react";

interface UseWebSocketReceiverOptions {
	url: string;
	onMessage: (data: any) => void;
	autoConnect?: boolean;
}

export const useWebSocket = (options: UseWebSocketReceiverOptions) => {
	const { url, onMessage, autoConnect = true } = options;
	const ws = useRef<WebSocket | null>(null);

	// URL 有效性校验函数
	const isValidWebSocketUrl = (url: string): boolean => {
		if (!url || typeof url !== "string") {
			return false;
		}

		try {
			const urlObj = new URL(url);
			return urlObj.protocol === "ws:" || urlObj.protocol === "wss:";
		} catch {
			return false;
		}
	};

	useMemo(() => {
		if (!autoConnect) return;

		// 校验 URL 有效性
		if (!isValidWebSocketUrl(url)) {
			console.error("Invalid WebSocket URL:", url);
			return;
		}

		// 创建WebSocket连接
		ws.current = new WebSocket(url);

		// 处理接收到的消息
		ws.current.onmessage = event => {
			try {
				// 尝试解析JSON，如果不是JSON就直接使用原始数据
				const data = JSON.parse(event.data);
				onMessage(data);
			} catch {
				onMessage(event.data);
			}
		};

		// 错误处理
		ws.current.onerror = error => {
			console.error("WebSocket error:", error);
		};

		// 连接关闭时的清理
		ws.current.onclose = () => {
			console.log("WebSocket connection closed");
		};
	}, [url]);

	useEffect(() => {
		// 组件卸载时断开连接
		return () => {
			if (ws.current) {
				ws.current.close();
				ws.current = null;
			}
		};
	}, []);

	// 断开连接的方法（可选）
	const disconnect = () => {
		if (ws.current) {
			ws.current.close();
			ws.current = null;
		}
	};

	return { disconnect };
};

export default useWebSocket;
